package com.morehair.config;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Locale;

/**
 * Author  kkw
 * Date  2021/6/8 11:19
 * Version 1.0
 * Description :
 */
public class CustomAuthenticator extends ModularRealmAuthenticator {
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        //父类拿过来的方法,对reams进行分发
        this.assertRealmsConfigured();
        Collection<Realm> originRealms = this.getRealms();
        MallToken token= (MallToken) authenticationToken;
        String type = token.getType();
        ArrayList<Realm> realms = new ArrayList<>();
        //瞒天过海,偷梁换柱
        for (Realm originRealm : originRealms) {
            if (originRealm.getName().toLowerCase(Locale.ROOT).contains(type)) {
                //对ream分发筛选
                realms.add(originRealm);
            }
        }

        return realms.size() == 1 ? this.doSingleRealmAuthentication((Realm)realms.iterator().next(), authenticationToken) : this.doMultiRealmAuthentication(realms, authenticationToken);
    }
}
